using ClosedXML.Excel;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using ProduceBasicData.Api.Application.Command.ProductionManage;
using ProduceBasicData.Api.Application.Command.ProductionManage.Plan;
using ProduceBasicData.Api.DTO.ProductionManage;
using ProduceBasicData.Domain.ProductionManage;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;
using System.Security.Claims;

namespace ProduceBasicData.Api.Controllers
{
    /// <summary>
    /// 生产管理
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ProductionManageController : ControllerBase
    {
        private readonly IMediator mediator;
        private readonly ILogger<ProductionManageController> logger;
        private readonly IBaseRespository<Work_order> work;

        public ProductionManageController(IMediator mediator, ILogger<ProductionManageController> logger, IBaseRespository<Work_order> work)
        {
            this.mediator = mediator;
            this.logger = logger;
            this.work = work;
        }

        /// <summary>
        /// 导出工单信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult ExportCraftMaintain()
        {
            try
            {
                // 1. 从数据源获取工单数据
                var craftMaintainList = work.GetAll(); // 假设的服务方法

                // 检查是否有数据可导出
                if (craftMaintainList == null || !craftMaintainList.Any())
                {
                    return NotFound("没有可导出的工单数据");
                }

                // 2. 创建Excel工作簿
                using (var workbook = new XLWorkbook())
                {
                    var worksheet = workbook.Worksheets.Add("工单数据");

                    // 3. 设置表头（根据工艺维护的实际字段定制）
                    var headers = new string[]
                    {
        "工单编码", "类型", "客户", "产品主数据", "产线","当前状态","工单描述", "计划开始时间", "计划结束时间","创建人","创建时间","修改人","修改时间"
                    };

                    // 添加表头并设置样式
                    for (int i = 0; i < headers.Length; i++)
                    {
                        var cell = worksheet.Cell(1, i + 1);
                        cell.Value = headers[i];
                        cell.Style.Font.Bold = true;
                        cell.Style.Fill.BackgroundColor = XLColor.FromHtml("#4472C4");
                        cell.Style.Font.FontColor = XLColor.White;
                        cell.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                    }

                    // 4. 填充数据
                    int row = 2; // 从第二行开始填充数据
                    foreach (var craft in craftMaintainList)
                    {
                        // 填充工艺维护数据（根据实际属性调整）
                        worksheet.Cell(row, 1).Value = craft.Order_no;
                        worksheet.Cell(row, 2).Value = craft.Work_type;
                        worksheet.Cell(row, 3).Value = craft.Customer_id;
                        worksheet.Cell(row, 4).Value = craft.Product_id;
                        worksheet.Cell(row, 5).Value = craft.Producttion_id;
                        worksheet.Cell(row, 6).Value = craft.Status;
                        worksheet.Cell(row, 7).Value = craft.Work_Desc;
                        worksheet.Cell(row, 8).Value = craft.Start_time;
                        worksheet.Cell(row, 9).Value = craft.End_time;
                        worksheet.Cell(row, 10).Value = craft.CreateName;
                        worksheet.Cell(row, 11).Value = craft.CreateTime;
                        worksheet.Cell(row, 12).Value = craft.UpdateName;
                        worksheet.Cell(row, 13).Value = craft.UpdateTime;
                        // 设置日期格式

                        if (craft.UpdateTime.HasValue)
                            worksheet.Cell(row, 13).Style.DateFormat.Format = "yyyy-MM-dd HH:mm";

                        row++;
                    }

                    // 5. 自动调整列宽
                    worksheet.Columns().AdjustToContents();

                    // 6. 添加筛选功能
                    worksheet.Range(1, 1, 1, headers.Length).SetAutoFilter();

                    // 7. 冻结首行
                    worksheet.SheetView.Freeze(1, 0);

                    // 8. 准备内存流
                    using (var stream = new MemoryStream())
                    {
                        workbook.SaveAs(stream);
                        stream.Position = 0;

                        // 9. 返回Excel文件
                        return File(
                            stream.ToArray(),
                            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                            $"工单数据_{DateTime.Now:yyyyMMddHHmmss}.xlsx"
                        );
                    }
                }
            }
            catch (Exception ex)
            {
                // 记录异常日志
                // _logger.LogError(ex, "导出工单数据时发生错误");
                return StatusCode(500, $"导出数据时发生错误: {ex.Message}");
            }
        }
        [HttpGet]
        public IActionResult GetText()
        {
            return Ok("完成");
        }
        /// <summary>
        /// 新增排班批量
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult<int>> CreateScheduling(Plan_SchedulingCreateCommand request)
        {
            return await mediator.Send(request);
        }
        /// <summary>
        /// 获取排班信息
        /// </summary>
        /// <param name="UserId">用户编号</param>
        /// <returns>返回任务</returns>
        [HttpGet]
        public Task<ApiResult<List<Plandto>>> GetScheduling(int UserId)
        {
            GetPlan_SchedulingCommand request = new GetPlan_SchedulingCommand();
            request.UserId = UserId;
            return mediator.Send(request);
        }
        /// <summary>
        /// 修改排班
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult<int>> UpdateScheduling(Plan_SchedulingUpdateCommand request)
        {
            return await mediator.Send(request);
        }
        /// <summary>
        /// 按日期范围获取排班信息
        /// </summary>
        /// <param name="UserId">用户编号</param>
        /// <param name="StartDate">开始日期（格式：yyyy-MM-dd）</param>
        /// <param name="EndDate">结束日期（格式：yyyy-MM-dd）</param>
        /// <returns>返回指定日期范围内的排班信息</returns>
        [HttpGet]
        public Task<ApiResult<List<Plandto>>> GetSchedulingByDateRange(int UserId, string StartDate, string EndDate)
        {
            GetPlan_SchedulingByDateRangeCommand request = new GetPlan_SchedulingByDateRangeCommand();
            request.UserId = UserId;
            request.StartDate = StartDate;
            request.EndDate = EndDate;
            return mediator.Send(request);
        }
        /// <summary>
        /// 删除排班
        /// </summary>
        /// <param name="Id">排班记录ID</param>
        /// <returns>返回操作结果</returns>
        [HttpGet]
        public Task<ApiResult<int>> DeleteScheduling(int Id)
        {
            DeletePlan_SchedulingCommand request = new DeletePlan_SchedulingCommand();
            request.Id = Id;
            return mediator.Send(request);
        }
        /// <summary>
        /// 获取产品信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns>返回任务</returns>
        [HttpGet]
        public Task<ApiResult<List<Productdto>>> GetProduct()
        {
            GetProductCommand request = new GetProductCommand();
            return mediator.Send(request);
        }
        /// <summary>
        /// 添加生产工单
        /// </summary>
        /// <param name="request">请求</param>
        /// <returns>返回任务</returns>
        [HttpPost]
        public async Task<ApiResult<int>> CreateWork(CreateWorkCommand request)
        {
            return await mediator.Send(request);
        }
        /// <summary>
        /// 修改生产工单
        /// </summary>
        /// <param name="request">请求</param>
        /// <returns>返回任务</returns>
        [HttpPost]
        public async Task<ApiResult<int>> UpdateWork(UpdateWorkCommand request)
        {
            return await mediator.Send(request);
        }
        /// <summary>
        /// 获取生产工单
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpGet]
        public Task<ApiPaging<WorkOrderDto>> GetWork([FromQuery]GetWorkCommand request)
        {
            return mediator.Send(request);  
        }
        /// <summary>
        /// 批量删除工单
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<ApiResult<int>> DeleteWork([FromQuery]DeleteWorkCommand request)
        {
            return await mediator.Send(request);
        }
    }
}
